<?php

include_once "baseChannel.php";
// 时间相差8小时
date_default_timezone_set("Asia/Shanghai");
class dali extends BaseChannel
{

    protected $appId;
    protected $appSecret;

    // 辅助加密参数
    public function __construct($options)
    {
        parent::__construct($options);
        $this->appId =  $options['appId'];
        $this->appSecret =  $options['appSecret'];
        // return
    }
    // 计算签名
    public function getSign($data)
    {
        // 排序
        $data['appSecret'] = $this->appSecret;
        ksort($data);
        $newData = http_build_query($data);
        $sign = md5(urldecode($newData));
        return $sign;
    }

    public function queryBalance($params = [])
    {
        $data = [];
        $data['appId'] = $this->appId;
        $data['timestamp'] = $this->getCurDate();
        $data['sign'] = $this->getSign($data);
        $return_str = $this->httpRequest($this->query_balance_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['code'] == 00) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['balance'] ?? 0, //余额
                'credit' => $return_data['creditQuota'] ?? 0, //授信 creditQuota
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['msg'] ?? '查询失败',
            'code' => 500
        ];
    }
    // params中 push_order_sn 为订单id   channel_order_sn 为第三方订单id
    // orderId与outOrderId至少填写1项，如都填写以orderId进行查询
    // 只支持查询当月订单、上月订单
    public function queryOrder($params)
    {
        $data = [];
        $data['appId'] = $this->appId;
        $data['outOrderId'] = $params['push_order_sn'];
        $data['orderId'] = $params['channel_order_sn'];
        $data['timestamp'] = $this->getCurDate();
        $data['sign'] = $this->getSign($data);
        $return_str = $this->httpRequest($this->query_order_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => json_encode($data), //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //处理中
        if ($return_data['code'] == 00 && $return_data['orderStatus'] == 1) {
            $ret['msg'] = '充值中';
        }
        // 成功
        if ($return_data['code'] == 00 && $return_data['orderStatus'] == 2) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['orderStatus'];
        }
        // 失败
        if ($return_data['code'] == 00 && $return_data['orderStatus'] == 3) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['orderDesc'];
        }

        // 不存在订单
        if ($return_data['code'] == 00 && $return_data['orderStatus'] == 4) {
            $ret['error'] = 1;
            $ret['code'] = 404;
            $ret['order_status'] = -1;
            $ret['msg'] = '订单不存在:' . $return_data['orderDesc'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $data = [];
        $data['appId'] = $this->appId;
        $data['outOrderId'] = $params['push_order_sn'];
        $data['uuid'] = $mobile;
        $data['itemId'] = $code;
        $data['timestamp'] = $this->getCurDate();
        $data['callbackUrl'] = urldecode($this->callback_url);
        $data['sign'] = $this->getSign($data);
        $return_str = $this->httpRequest($this->submit_order_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['orderId'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' => $return_data['cost'] ?? null,
            'channel_balance' => null,
        ];
        if ($return_data['code'] == 00) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['msg'] ?? '下单成功';
        } else {
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['msg'] ?? '下单失败';
            }
        }

        return $ret;
    }
    public function callback($params)
    {
        //        $post = $this->decrypt($params, $this->appSecret);

        $post = $params;
        $this->callback_params = $post;

        $this->channel_order_sn = $post['orderId'];
        $this->push_order_sn = $post['outOrderId'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $post['orderStatus'];
        $msg = $post['orderDesc'];
        //凭证
        $pz =  '';

        // 验证签名
        $paramsSign = $params['sign'];
        unset($params['sign']);
        $sign = $this->getSign($params);

        if ($sign != $paramsSign) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            return $res;
        }
        if ($order_status == 2) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = 'ok';
        }
        if ($order_status == 3) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }

        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate()
    {
        $time = $this->msectime();
        $timestamp = date('YmdHis') . substr($time, -3);
        // var_dump(date('YmdHis'));
        return $timestamp;
    }
    public function decrypt($data, $key)
    {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
    }
}
